<template>
  <div class="manage">
    <el-dialog :title="operateType === 'add' ? '新增用户' : '更新用户'" :visible.sync="isShow">
      <template>
        <el-form :inline="false" :model="operateForm" :rules="operateRules" ref="operateForm" label-width="100px">
          <el-form-item key="userName" label="用户名称" prop="userName">
            <el-input v-model="operateForm.userName" placeholder="请输入用户名称" ></el-input>
          </el-form-item>

          <el-form-item key="realName" label="姓名" prop="realName">
            <el-input v-model="operateForm.realName" placeholder="请输入姓名" ></el-input>
          </el-form-item>

          <el-form-item key="birth" label="出生日期" prop="birth">
            <el-date-picker v-model="operateForm.birth" placeholder="选择日期" value-format="yyyy-MM-dd"> </el-date-picker>
          </el-form-item>

          <el-form-item key="sex" label="性别" prop="sex">
            <el-select v-model="operateForm.sex" placeholder="请选择性别" v-if="'select'">
              <el-option v-for="item in sexArray" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item key="userEdu" label="教育" prop="userEdu">
            <el-select v-model="operateForm.userEdu" placeholder="请选择教育" v-if="'select'">
              <el-option v-for="item in userEduArray" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item key="phoneNum" label="手机号" prop="phoneNum">
            <el-input v-model="operateForm.phoneNum" placeholder="请输入手机号" ></el-input>
          </el-form-item>

          <el-form-item key="email" label="邮箱" prop="email">
            <el-input v-model="operateForm.email" placeholder="请输入邮箱"  ></el-input>
          </el-form-item>

          <el-form-item key="deptId" label="所属部门" prop="deptId">
            <tree-select :height="400"
                         :width="400"
                         size="small"
                         :data="treeData"
                         :defaultProps="defaultProps"
                         :nodeKey="nodeKey"
                         :checkedKeys="defaultCheckedKeys"
                         clearable
                         collapseTags
                         checkStrictly ref="tree">
            </tree-select>
          </el-form-item>

          <el-form-item key="roleIds" label="角色分配" prop="roleIds">
            <el-select
                    v-model="operateForm.roleIds"
                    multiple
                    collapse-tags
                    placeholder="请选择">
              <el-option
                      v-for="item in roles"
                      :key="item.id"
                      :label="item.roleName"
                      :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item><slot></slot></el-form-item>
        </el-form>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="confirm('operateForm')">确 定</el-button>
      </div>
    </el-dialog>
    <div class="manage-header">
      <template>

          <el-button type="primary" @click="addUser()">+ 新增</el-button>

        <el-form :inline="true" :model="searchFrom" ref="searchFrom" label-width="100px">
          <el-form-item key="keyword" label="用户名">
            <el-input v-model="searchFrom.userName" placeholder="请输入用户名" ></el-input>
          </el-form-item>
          <el-form-item key="phoneNum" label="手机号" prop="phoneNum">
            <el-input v-model="searchFrom.phoneNum" placeholder="请输入手机号" ></el-input>
          </el-form-item>
          <el-form-item key="realName" label="姓名" prop="realName">
            <el-input v-model="searchFrom.realName" placeholder="请输入姓名" ></el-input>
          </el-form-item>
          <el-form-item key="userEdu" label="教育" prop="userEdu">
            <el-select v-model="searchFrom.userEdu" placeholder="请选择教育" v-if="'select'">
              <el-option v-for="item in userEduArray" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item key="email" label="邮箱" prop="email">
            <el-input v-model="searchFrom.email" placeholder="请输入邮箱"  ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="getList()">搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="resetForm('searchFrom')">重置</el-button>
          </el-form-item>
        </el-form>


      </template>

    </div>
    <common-table :tableData="tableData" :tableLabel="tableLabel" :config="config" @changePage="getList()" @edit="editUser" @del="delUser"></common-table>
  </div>
</template>

<script>
import CommonTable from '../../components/CommonTable'
import TreeSelect from '../../components/TreeSelect'

import store from "@/store";
export default {
  components: {
    CommonTable,
    TreeSelect
  },
  data() {

    //自定义的邮箱和手机验证规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的手机号"));
    };
    return {
      operateType: 'add',
      isShow: false,
      showCheckbox:true,
      defaultProps: {
        parent: 'parentId',   // 父级唯一标识
        value: 'id',          // 唯一标识
        label: 'deptName',       // 标签显示
        children: 'children', // 子级
      },
      nodeKey: 'id',
      defaultCheckedKeys: [],
      treeData:[],
      tableData: [],
      roles:[],
      tableLabel: [
        {
          prop: 'userName',
          label: '用户名'
        },
        {
          prop: 'password',
          label: '密码'
        },
        {
          prop: 'realName',
          label: '姓名'
        },
        {
          prop: 'age',
          label: '年龄',
          width: 200
        },
        {
          prop: 'sexLabel',
          label: '性别'
        },
        {
          prop: 'userEduLabel',
          label: '教育水平',
          width: 200
        },
        {
          prop: 'phoneNum',
          label: '手机号',
          width: 200
        },
        {
          prop: 'email',
          label: '邮箱',
          width: 200
        }

      ],
      config: {
        page: 1,
        total: 30,
        pageSize:10,
        loading: false
      },
      userEduLabelObj: {
        "01":"博士研究生",
        "02":"硕士研究生",
        "03":"本科",
        "04":"大专",
        "05":"中专/技校",
        "06":"高中/职高",
        "07":"初中",
        "08":"小学",
        "09":"无"
      },
      userEduArray: [
        {
          label: '请选择',
          value: ''
        },
        {
          label: '博士研究生',
          value: '01'
        },
        {
          label: '硕士研究生',
          value: '02'
        },
        {
          label: '本科',
          value: '03'
        },
        {
          label: '大专',
          value: '04'
        },
        {
          label: '中专/技校',
          value: '05'
        },
        {
          label: '高中/职高',
          value: '06'
        },
        {
          label: '初中',
          value: '07'
        },
        {
          label: '小学',
          value: '08'
        },
        {
          label: '无',
          value: '09'
        }
      ],
      sexLabelObj: {
        '1':'男',
        '2':'女',
        '3':'未知'
      },
      sexArray:[
        {
          label: '男',
          value: '1'
        },
        {
          label: '女',
          value: '2'
        },
        {
          label: '未知',
          value: '3'
        }
      ],
      operateForm: {
        userName: '',
        password: '',
        realName: '',
        age: '',
        birth: '',
        userEdu: '',
        phoneNum: '',
        email: '',
        deptId:'',
        roleIds:[]
      },
      operateRules:{
        userName: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          { min: 6, max: 20, message: '用户名长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        realName: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        birth: [
          {required: true, message: '请选择出生日期', trigger: 'change' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        userEdu: [
          { required: true, message: '请选择教育', trigger: 'change' }
        ],
        phoneNum: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: checkMobile,
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入地址", trigger: "blur" },
        ]
      },
      searchFrom: {
        userName: '',
        realName: '',
        userEdu: '',
        phoneNum: '',
        email: '',
        deptId:'',
        deptName:''
      }
    }
  },
  methods: {
    getList() {
      this.config.loading = true
      // 搜索时，页码需要设置为1，才能正确返回数据，因为数据是从第一页开始返回的
      store.commit('getToken')
      let token = store.state.user.token

      this.$http
        .get('http://localhost:8001/api/manager/user/list', {
          params: {
            page: this.config.page,
            pageSize: this.config.pageSize,
            searchUser: this.searchFrom
          },
          headers: {
            "token": token
          }
        })
        .then(res => {
          this.tableData = res.data.records.map(item => {
            // 转换
            item.sexLabel = this.sexLabelObj[item.sex]
            item.userEduLabel = this.userEduLabelObj[item.userEdu];
            return item
          })
          this.config.total = res.data.total
          this.config.loading = false
        })
    },
    getTreeData(deptName = '') {
      this.config.loading = true
      store.commit('getToken')
      let token = store.state.user.token
      this.$http
              .get('http://localhost:8001/api/manager/dept/listDeptTree', {
                params: {
                  deptName
                },
                headers: {
                  "token": token
                }
              })
              .then(res => {
                res = res.data;
                if (res.code === 20000) {
                  this.treeData = res.data;
                } else {
                  this.$message({
                    type: 'error',
                    message: res.message
                  })
                }
                this.config.loading = false
              })
    },
    getRoles() {
      this.config.loading = true
      store.commit('getToken')
      let token = store.state.user.token
      this.$http
              .get('http://localhost:8001/api/manager/role/listAll', {
                headers: {
                  "token": token
                }
              })
              .then(res => {
                res = res.data;
                if (res.code === 20000) {
                  this.roles = res.data;
                } else {
                  this.$message({
                    type: 'error',
                    message: res.message
                  })
                }
                this.config.loading = false
              })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    addUser() {
      this.operateForm = {}
      this.operateType = 'add'
      this.defaultCheckedKeys = [];
      this.isShow = true
    },
    editUser(row) {
      this.operateType = 'edit'
      this.isShow = true
      this.operateForm = row
      this.operateForm.roleIds = [];
      if (row.deptId) {
        this.defaultCheckedKeys = [row.deptId];
      } else {
        this.defaultCheckedKeys = [];
      }
      if (row.roles) {
        row.roles.forEach(item => {
          this.operateForm.roleIds.push(item.id)
        })
      }
    },
    confirm(form) {
      this.operateForm.deptId = this.$refs.tree.selectedData;
      this.$refs[form].validate((valid) => {
        if (valid) {
          store.commit('getToken')
          let token = store.state.user.token
          if (this.operateType === 'edit') {
            console.log(this.operateForm)
            this.$http.post('http://localhost:8001/api/manager/user/update', this.operateForm, {
              headers:{
                "token":token
              }
            }).then(res => {
              console.log(res.data)
              this.isShow = false
              this.getList()
            })
          } else {
            console.log(this.operateForm)
            this.$http.post('http://localhost:8001/api/manager/user/save', this.operateForm, {
              headers:{
                "token":token
              }
            }).then(res => {
              console.log(res.data)
              this.isShow = false
              this.getList()
            })
          }
        }
      });

    },
    delUser(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          store.commit('getToken')
          let token = store.state.user.token
          this.$http
            .delete('http://localhost:8001/api/manager/user/delete/' + row.id, {
              headers: {
                token
              }
            })
            .then(res => {
              console.log(res.data)
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getList()
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  },
  created() {
    this.getList()
    this.getTreeData();
    this.getRoles();
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/scss/common';
</style>
